#pragma once
#include <ctime>
#include <vector>
#include <cassert>
#include <sstream>
#include "level.hpp"
#include "message.hpp"

namespace  bitlog
{
    // 抽象格式化 子项基类
    class FormatIntem
    {
    public:
        using ptr = std::shared_ptr<FormatIntem>;
        virtual void format(std::ostream& out, const LogMsg& msg) = 0;
    };

    class MsgFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << msg._payload;
        }
    };

    class LevelFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };

    class TimeFormatIntem : public FormatIntem
    {
    public:
        TimeFormatIntem(const std::string& fmt = "%H:%M:%S")
            :_time_fmt(fmt)
        {}

        void format(std::ostream& out, const LogMsg& msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            out << tmp;
        }
    private:
        std::string _time_fmt;
    };

    class FileFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << msg._file;
        }
    };

    class LineFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << msg._line;
        }
    };

    class ThreadFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << msg._tid;
        }
    };

    class LoggerFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << msg._logger;
        }
    };

    class TabFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatIntem : public FormatIntem
    {
    public:
        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << "\n";
        }
    };

    class OtherFormatIntem : public FormatIntem
    {
    public:
        OtherFormatIntem(const std::string& str)
            :_str(str)
        {}

        void format(std::ostream& out, const LogMsg& msg) override
        {
            out << _str;
        }
    private:
        std::string _str;
    };


    /*
        %d 表示日期,包含字串 {%H:%N:%S}
        %t 表示日期
        %c 表示日志器名称
        %f 表示源码文件名
        %l 表示源码行号
        %p 表示日志级别
        %T 表示制表符缩进
        %m 表示主体消息
        %n 表示换行
    */
    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;

        Formatter(const std::string& pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            :_pattern(pattern)
        {
            assert(parsePattern());
        }

        // 对msg进行格式化
        void format(std::ostream& out, const LogMsg& msg)
        {
            for (auto& it : _items)
            {
                it->format(out, msg);
            }
        }

        std::string format(const LogMsg& msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }
    private:
        bool parsePattern()
        {
            // 1.对格式化规则进行字符串解析
            // abc[%d{%H:%M:%S}][%p]%T%m%n
            std::vector<std::pair<std::string, std::string>> fmt_order;
            size_t pos = 0;
            std::string key, val;
            while (pos < _pattern.size())
            {
                // 1.处理原始字符串 -- 判断是不是%, 不是就是原始字符
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }
                // 能走下来就代表pos位置是%字符  %%处理为一个字符
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                // 走下来,代表%后面是个格式化字符, 代表原始字符串处理完毕
                if (val.empty() == false)
                {
                    fmt_order.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 格式化字符串处理 pos -> %
                pos += 1;
                if (pos == _pattern.size())
                {
                    std::cout << "%之后,没有对应的格式化字符!\n";
                    return false;
                }

                key = _pattern[pos];
                pos += 1;
                if (pos <_pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1; // pos指向子规则的起始位置
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    // 走下来之后跳出了循环,没有},代表格式错误
                    if (pos == _pattern.size())
                    {
                        std::cout << "子规则{}匹配错误\n";
                        return false;
                    }
                    pos += 1;  // 走到下次处理的位置
                }
                fmt_order.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            // 2.根据解析得到的数据初始化子项数组成员
            for (auto& it : fmt_order)
                _items.push_back(createItem(it.first, it.second));
            return true;
        }

        // 根据不同的格式化字符串创建不同的格式化子项对象
        FormatIntem::ptr createItem(const std::string& key, const std::string& val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatIntem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormatIntem>();
            if (key == "c")
                return std::make_shared<LoggerFormatIntem>();
            if (key == "f")
                return std::make_shared<FileFormatIntem>();
            if (key == "l")
                return std::make_shared<LineFormatIntem>();
            if (key == "p")
                return std::make_shared<LevelFormatIntem>();
            if (key == "T")
                return std::make_shared<TabFormatIntem>();
            if (key == "m")
                return std::make_shared<MsgFormatIntem>();
            if (key == "n")
                return std::make_shared<NLineFormatIntem>();
            if (key == "")
                return std::make_shared<OtherFormatIntem>(val);

            std::cout << "没有对应的格式化字符串: %" << key << std::endl;
            abort();
            return FormatIntem::ptr();
        }
    private:
        std::string _pattern; // 格式化规则的字符串
        std::vector<FormatIntem::ptr> _items;
    };
}
